package com.wws.family.ui.activity

import android.animation.ObjectAnimator
import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.github.gzuliyujiang.wheelpicker.DatePicker
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.github.gzuliyujiang.wheelpicker.impl.UnitDateFormatter
import com.github.gzuliyujiang.wheelpicker.widget.DateWheelLayout
import com.wika.basics.base.BaseActivity
import com.wika.basics.ext.divider
import com.wika.basics.ext.toColorSpan
import com.wika.basics.ext.vertical
import com.wws.family.R
import com.wws.family.adapter.AccountAdapter
import com.wws.family.databinding.ActivityAccountBinding
import com.wws.family.db.AccountBean
import com.wws.family.db.WiKaDataBase
import com.wws.family.dialog.AccountInputDialog
import com.wws.family.dialog.CommonDialog
import com.wws.family.utils.DateUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.DecimalFormat


/**
 *@Description:账本页面
 *@Date: 2025/1/8 15:35
 *@Author: WangWeiShuo
 */
class AccountActivity: BaseActivity<ActivityAccountBinding>() {
    private var accountList = mutableListOf<AccountBean>()
    private var accountAdapter: AccountAdapter? = null
    private var selectYear = 2025
    private var selectMonth = 1
    private var currentType = 0
    private var startRotation = 0f
    private var stopRotation = 180f
    private var expensesPrice = 0.0
    private var incomePrice = 0.0
    private val decimalFormat = DecimalFormat("#.00")

    override fun initView(savedInstanceState: Bundle?) {
//        setActionBar(R.drawable.baseline_arrow_back,"账本",R.color.black,R.color.blue_B8DCFF,R.drawable.icon_add,true,false)
        setStatusBar(false,getColor(R.color.blue_B8DCFF),false)
        mBinding.rgExpIncome.setOnCheckedChangeListener { group, checkedId ->
            when(checkedId){
                R.id.rb_expenses -> {
                    currentType = 0
                }
                R.id.rb_income -> {
                    currentType = 1
                }
            }
            initAccountInfo(true,true,true)
        }
        mBinding.rbExpenses.isChecked = true
        mBinding.toolbarBack.setOnClickListener {
            finish()
        }
        mBinding.toolbarBtnRight.setOnClickListener {
            showInputDialog()
        }
        mBinding.llYearMonth.setOnClickListener {
            selectYearMonth()
        }
    }

    override fun initData() {
        selectYear = DateUtils.getCurrentYear()
        selectMonth = DateUtils.getCurrentMonth()
        mBinding.tvYear.text = "${selectYear}年"
        mBinding.tvMonth.text = "${selectMonth}月"
        initAccountInfo(true,true,true)
    }

    override fun needFullScreen(): Boolean {
        return false
    }

    override fun actionBarRightClick() {
    }

    private fun initAccountInfo(needLoadList: Boolean,needLoadExp: Boolean,needLoadIncome: Boolean){
        lifecycleScope.launch(Dispatchers.IO){
            if(needLoadList) {
                accountList = WiKaDataBase.getInstance().accountDao()
                    .getAccountInfoByTypeYear(currentType, selectYear, selectMonth)
                withContext(Dispatchers.Main) {
                    showAccountInfo()
                }
            }
            if(needLoadExp) {
                delay(200)
                expensesPrice = WiKaDataBase.getInstance().accountDao()
                    .getAccountPrice(0, selectYear, selectMonth)
                withContext(Dispatchers.Main) {
                    mBinding.tvExpensesCount.text = "$expensesPrice"
                }
            }
            if(needLoadIncome) {
                delay(200)
                incomePrice = WiKaDataBase.getInstance().accountDao()
                    .getAccountPrice(1, selectYear, selectMonth)
                withContext(Dispatchers.Main) {
                    mBinding.tvIncomeCount.text = "$incomePrice"
                    val differ = incomePrice - expensesPrice
                    if (differ == 0.0){
                        mBinding.tvIncomeExp.text = "${incomePrice - expensesPrice}"
                    }else{
                        mBinding.tvIncomeExp.text = "${decimalFormat.format(incomePrice - expensesPrice)}"
                    }
                }
            }
        }
    }

    private fun checkData(){
        if(accountList.isNullOrEmpty()){
            mBinding.ivNoData.visibility = View.VISIBLE
            mBinding.rvAccount.visibility = View.INVISIBLE
        }else{
            mBinding.ivNoData.visibility = View.INVISIBLE
            mBinding.rvAccount.visibility = View.VISIBLE
        }
    }


    private fun showAccountInfo(){
        checkData()
        if(accountAdapter == null){
            accountAdapter = AccountAdapter(this)
            mBinding.rvAccount.vertical()
//            mBinding.rvAccount.divider(color = getColor(R.color.gray_f0f0f0), paddingSize = 60, includeLast = false)
            mBinding.rvAccount.adapter = accountAdapter
        }
        accountAdapter?.setData(accountList)
        accountAdapter?.addDeleteCallBack(object : AccountAdapter.OnDeleteCallBack{
            override fun onDelete(pos: Int, itemBean: AccountBean?) {
                showDeleteDialog(pos, itemBean)
            }
        })
    }

    private fun setImageRotation(){
        val animator: ObjectAnimator = ObjectAnimator.ofFloat(
            mBinding.ivArrowDownUp,
            "rotation", startRotation,stopRotation
        )
        animator.duration = 500
        animator.start()
        if(startRotation == 0f){
            startRotation = 180f
            stopRotation = 0f
        }else{
            startRotation = 0f
            stopRotation = 180f
        }
    }

    private fun selectYearMonth() {
        setImageRotation()
        val picker = DatePicker(this)
        //picker.setBodyWidth(240);
        val wheelLayout: DateWheelLayout = picker.wheelLayout
        wheelLayout.setDateMode(DateMode.YEAR_MONTH)

        picker.setOnDatePickedListener { year, month, day ->
            selectYear = year
            selectMonth = month
            initData()
            initAccountInfo(true,true,true)
        }
        picker.setOnDismissListener {
            setImageRotation()
        }
        wheelLayout.setDateFormatter(UnitDateFormatter())
        //wheelLayout.setRange(DateEntity.target(2021, 1, 1), DateEntity.target(2050, 12, 31), DateEntity.today());
        wheelLayout.setRange(DateEntity.target(2020, 1, 1), DateEntity.today(), DateEntity.today())
        picker.wheelLayout.setResetWhenLinkage(false)
        picker.show()
    }

    private fun showInputDialog(){
        AccountInputDialog.Builder(this).showContent(currentType).addSaveListener(object : AccountInputDialog.OnSaveListener{
            override fun onSave(name: String, time: String, price: Double,expType: String,year: Int,month: Int) {
                lifecycleScope.launch(Dispatchers.IO){
                    val accountBean = AccountBean(name,time,currentType,price,expType,year,month,DateUtils.getNowDateTimeForLong())
                    WiKaDataBase.getInstance().accountDao().insert(accountBean)
                    delay(300)
                    withContext(Dispatchers.Main){
                        accountList.add(0,accountBean)
                        checkData()
                        if(selectYear == year && selectMonth == month) {
                            if (accountAdapter != null) {
                                accountAdapter?.setItem(0, accountBean)
                            }
                            if(currentType == 0) {
                                initAccountInfo(false,true,false)
                            }else{
                                initAccountInfo(false,false,true)
                            }
                        }
                    }
                }
            }

        }).show()
    }

    private fun showDeleteDialog(pos: Int, itemBean: AccountBean?){
        val deleteValue = "是否删除${itemBean?.name}?"
        val deleteContent = deleteValue.toColorSpan(IntRange(4,deleteValue.length - 1),getColor(R.color.red_DD2C00))
        CommonDialog.Builder(this).showTitle("删除提示").showContent(deleteContent)
            .setOnSureListener {
                accountList.removeAt(pos)
                if(accountAdapter != null){
                    accountAdapter?.removeAt(pos)
                }
                checkData()
                lifecycleScope.launch(Dispatchers.IO){
                    WiKaDataBase.getInstance().accountDao().deleteByKey(itemBean?.accountKey!!)
                }
            }.show()
    }
}